package com.example.blogdemo.controller;

import com.example.blogdemo.entity.Archive;
import com.example.blogdemo.entity.HostHolder;
import com.example.blogdemo.entity.User;
import com.example.blogdemo.entity.ViewObject;
import com.example.blogdemo.service.ArchiveService;
import com.example.blogdemo.service.JedisService;
import com.example.blogdemo.util.RedisKeyUntil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Anita
 * @Date 2017/12/21 17:28
 */
@Controller
public class ArchiveController {

    @Autowired
    private ArchiveService archiveService;

    @Autowired
    private JedisService jedisService;

    @Autowired
    private HostHolder hostHolder;

    @RequestMapping("/archive")
    public String archive(Model model, @RequestParam("userId")Integer userId){
        List<Archive>  archives = archiveService.selectArticleGroupByTime(userId);
        Map<String,List<Archive>> map = new HashMap<>();
        for(Archive archive:archives){
            String date = archive.getYear()+"-"+archive.getMonth();
            List<Archive> list = map.getOrDefault(date,new ArrayList<>());
            list.add(archive);
            map.put(date,list);
        }

        List<ViewObject> vos = new ArrayList<>();
        for(Map.Entry entry:map.entrySet()){
            ViewObject vo = new ViewObject();
            vo.set("date",entry.getKey());
            vo.set("list",entry.getValue());
            vos.add(vo);
        }
        model.addAttribute("vos",vos);

        ViewObject clickCount = new ViewObject();
        String currentPage = jedisService.get(RedisKeyUntil.getClickCountKey("/archive"));
        String sumPage = jedisService.get(RedisKeyUntil.getClickCountKey("SUM"));
        clickCount.set("currentPage",currentPage);
        clickCount.set("sumPage",sumPage);
        model.addAttribute("clickCount",clickCount);

        User user = hostHolder.getUser();
        if(user==null||"admin".equals(user.getRole())){
            model.addAttribute("create",1);
        }else{
            model.addAttribute("create",0);
        }

        return "archive";
    }

}
